package com.feiyisys.controller;

import com.feiyisys.bo.UpdateVideoStatusBO;
import com.feiyisys.common.PageResult;
import com.feiyisys.common.Result;
import com.feiyisys.dto.*;
import com.feiyisys.entity.User;
import com.feiyisys.entity.Video;
import com.feiyisys.handlers.BaseContext;
import com.feiyisys.service.UserService;
import com.feiyisys.utils.TencentCosUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 普通用户账号信息表 前端控制器
 * </p>
 *
 * @author wq
 * @since 2025-10-10
 */
@RestController
@RequestMapping("/user")
@Slf4j
@CrossOrigin("*")
public class UserController {
    @Resource
    private UserService userService;

    @Resource
    private TencentCosUtil tencentCosUtil;

    @PostMapping("/login")
    public Result<String> login(@RequestBody UserLoginDTO userLoginDTO) {
        String token = userService.login(userLoginDTO);
        if(token.equals("账号被禁用，请联管理员")){
            return Result.fail(token);
        }
        return Result.success(token);
    }


    @PostMapping("/register")
    public Result<Object> register(@RequestBody User user) {
        userService.saveUser(user);
        return Result.success();
    }

    @GetMapping("/info")
    public Result<User> getUserInfo() {
        Long id = BaseContext.getCurrentId();
        User user = userService.getById(id);
        return Result.success(user);
    }


    @PostMapping("/updateUserInfo")
    public Result<Object> updateUserInfo(@RequestBody UpUserDTO upUserDTO) {
        userService.updateInfo(upUserDTO);
        return Result.success();
    }

    @PostMapping("/upload")
    public Result<String> uploadPicture(@RequestParam("file") MultipartFile file) {
        try {
            // 上传文件到腾讯云COS
            String key = tencentCosUtil.uploadFile(file);
            // 获取文件完整访问URL
            String fileUrl = tencentCosUtil.getFileUrl(key);
            log.info("文件上传成功, URL: {}", fileUrl);
            return Result.success(fileUrl);
        } catch (Exception e) {
            log.error("文件上传失败: {}", e.getMessage());
            return Result.fail("文件上传失败: " + e.getMessage());
        }
    }

    @PostMapping("findPage")
    public PageResult<User> findPage(@RequestBody FindUPageDTO findUPageDTO){
        return PageResult.success(userService.findPage(findUPageDTO));
    }

    @PutMapping("/isUse")
    public Result<Object> updateIsUse(@RequestBody UpdateUserStatusDTO updateUserStatusDTO) {
        return Result.success(userService.updateIsUse(updateUserStatusDTO));
    }
    @PostMapping("/findPwd")
    public Result<String> findPwd(@RequestBody String email) {
        return Result.success(userService.findPwd(email));
    }

    @GetMapping("/{id}")
    public Result<User> getUserById(@PathVariable Long id) {
        User user = userService.getById(id);
        return Result.success(user);
    }

}
